package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.FamilyMember;
import com.hnichr.ump.common.talent.library.service.FamilyMemberService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class FamilyMemberSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "familyMemberList";

    @Autowired
    private FamilyMemberService familyMemberService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray familyList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(familyList)){
            return;
        }
        for(Object familyObject:familyList){
            if(familyObject instanceof JSONObject){
                JSONObject family = (JSONObject) familyObject;
                FamilyMember familyMember = new FamilyMember();
                familyMember.setId(family.getString("id"));
                familyMember.setDelFlag(family.getBoolean("delFlag"));
                familyMember.setUserId(family.getString("userId"));
                if(family.containsKey("createTime")){
                    familyMember.setOrginalCreateTime(new Date(family.getLong("createTime")));
                }
                if(family.containsKey("updateTime")){
                    familyMember.setOrginalUpdateTime(new Date(family.getLong("updateTime")));
                }

                familyMember.setAppellation(family.getString("appellation"));
                familyMember.setName(family.getString("name"));
                familyMember.setAge(family.getInteger("age"));
                familyMember.setCompany(family.getString("company"));
                familyMember.setPosition(family.getString("position"));
                familyMember.setPolitics(family.getString("politics"));
                familyMember.setRemark(family.getString("remark"));
                familyMember.setEducation(family.getString("education"));
                if(family.containsKey("birthday")){
                    familyMember.setBirthday(new Date(family.getLong("birthday")));
                }
                familyMember.setPhone(family.getString("phone"));
                familyMember.setResumeId(family.getString("resumeId"));
                familyMember.setSyncDate(syncDate);
                familyMemberService.merge(familyMember);
            }
        }
    }
}
